package logica;

import java.net.DatagramPacket;
import java.net.InetAddress;
import java.net.UnknownHostException;

import exceptions.ConexionException;

public class Emisor extends Nodo {
	
	public Emisor() throws ConexionException {
		super();
	}
	
	public Emisor (int _puerto) throws ConexionException {
		super (_puerto);
	}

	public boolean enviarMensaje(String msg, String addressIp, int _puerto)
	{
		boolean ok;
		byte[] buffer = msg.getBytes();
		
		InetAddress address;
		try {			
			address = InetAddress.getByName(addressIp);

			DatagramPacket packet = new DatagramPacket(
				buffer, buffer.length, address, _puerto
			);
			
			getSocket().setBroadcast(addressIp.equals("255.255.255.255"));
			getSocket().send(packet);
			ok = true;
		} catch (Exception e) {
			e.printStackTrace();
			ok = false;
		}
		return ok;
	}
	
	public String getIpEmisor()
	{
		String miIp = null;
		try {
			miIp = InetAddress.getLocalHost().getHostAddress();
		} catch (UnknownHostException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
			miIp = "desconocida";
		}
		return miIp;
	}
}
